package com.zhouyibike.uu.ui.activity.hehuoren;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.gyf.barlibrary.OnKeyboardListener;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.config.Config;
import com.zhouyibike.uu.entity.CityBikeCompanyStardantInterfaceResult;
import com.zhouyibike.uu.entity.GetCodeResult;
import com.zhouyibike.uu.http.ApiCallback;
import com.zhouyibike.uu.ui.activity.web.TotalWebActivity;
import com.zhouyibike.uu.ui.adapter.MytablayoutvpAdapter;
import com.zhouyibike.uu.ui.base.BaseActivity;
import com.zhouyibike.uu.utils.Util;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ChengshihehuorenActivity extends BaseActivity {
    private TabLayout tabs;
    private ViewPager viewPager;
    private List<String> mTitle = new ArrayList<String>();
    private List<Fragment> mFragment = new ArrayList<Fragment>();
    private MyhehuorenFragment f1, f2, f3, f4, f5, f6, f7, f8;
    private MytablayoutvpAdapter adpater;
    private LinearLayout hehuorenmingxily;
    private ImageView fanhui, mingxi;
    private TextView hehuoren_weizhitv, hehuoren_zongshourutv, hehuoren_quyudanchegouliangtv, gotixian;
    private double cantixianmoney = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chengshihehuoren);
        settitle();
        initview();
        initdata();
        initlistener();
    }

    private void initlistener() {
        hehuorenmingxily.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChengshihehuorenActivity.this, ChengshihehuorenmingxiActivity.class);
                startActivity(intent);
            }
        });
        fanhui.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        gotixian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ChengshihehuorenActivity.this, HehuorenTixiannewActivity.class);
                intent.putExtra("cantixianmoney", cantixianmoney);
                startActivityForResult(intent, 200);
            }
        });
        mingxi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                backgroundAlpha(0.6f);
                showpop(mingxi);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == 200) {
            dataf();
        }
    }

    private void initdata() {
        mTitle.add("七日合伙人收益");
        mTitle.add("七日区域单车购买量");
        f1 = new MyhehuorenFragment();
        f2 = new MyhehuorenFragment();
//        f3 = new MyBikeFragment();
//        f4 = new MyBikeFragment();
        getMsg();
    }

    private void initview() {
        mingxi = (ImageView) findViewById(R.id.mingxi);
        gotixian = (TextView) findViewById(R.id.gotixian);
        hehuoren_quyudanchegouliangtv = (TextView) findViewById(R.id.hehuoren_quyudanchegouliangtv);
        hehuoren_zongshourutv = (TextView) findViewById(R.id.hehuoren_zongshourutv);
        hehuoren_weizhitv = (TextView) findViewById(R.id.hehuoren_weizhitv);
        viewPager = (ViewPager) findViewById(R.id.hehuorenvp);
        tabs = (TabLayout) findViewById(R.id.hehuorentablayout);
        hehuorenmingxily = (LinearLayout) findViewById(R.id.hehuorenmingxily);
        fanhui = (ImageView) findViewById(R.id.fanhui);
    }

    public void reflex(final TabLayout tabLayout) {
        //了解源码得知 线的宽度是根据 tabView的宽度来设置的
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                try {
                    //拿到tabLayout的mTabStrip属性
                    LinearLayout mTabStrip = (LinearLayout) tabLayout.getChildAt(0);

                    int dp10 = Util.dp2px(tabLayout.getContext(), 30);

                    for (int i = 0; i < mTabStrip.getChildCount(); i++) {
                        View tabView = mTabStrip.getChildAt(i);

                        //拿到tabView的mTextView属性  tab的字数不固定一定用反射取mTextView
                        Field mTextViewField = tabView.getClass().getDeclaredField("mTextView");
                        mTextViewField.setAccessible(true);

                        TextView mTextView = (TextView) mTextViewField.get(tabView);

                        tabView.setPadding(0, 0, 0, 0);

                        //因为我想要的效果是   字多宽线就多宽，所以测量mTextView的宽度
                        int width = 0;
                        width = mTextView.getWidth();
                        if (width == 0) {
                            mTextView.measure(0, 0);
                            width = mTextView.getMeasuredWidth();
                        }

                        //设置tab左右间距为10dp  注意这里不能使用Padding 因为源码中线的宽度是根据 tabView的宽度来设置的
                        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) tabView.getLayoutParams();
                        params.width = width;
                        params.leftMargin = dp10;
                        params.rightMargin = dp10;
                        tabView.setLayoutParams(params);

                        tabView.invalidate();
                    }

                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    private void settitle() {
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT)//4.9
        {
        } else {
            ImmersionBar.with(this)
                    .transparentStatusBar()  //透明状态栏，不写默认透明色
                    //  .transparentNavigationBar()  //透明导航栏，不写默认黑色(设置此方法，fullScreen()方法自动为true)
                    //   .transparentBar()             //透明状态栏和导航栏，不写默认状态栏为透明色，导航栏为黑色（设置此方法，fullScreen()方法自动为true）
                    .statusBarColor(R.color.radio_button_selected_color)     //状态栏颜色，不写默认透明色
                    //  .navigationBarColor(R.color.colorPrimary) //导航栏颜色，不写默认黑色
                    //   .barColor(R.color.colorPrimary)  //同时自定义状态栏和导航栏颜色，不写默认状态栏为透明色，导航栏为黑色
                    //  .statusBarAlpha(1f)  //状态栏透明度，不写默认0.0f
//                .navigationBarAlpha(0.4f)  //导航栏透明度，不写默认0.0F
//                .barAlpha(0.3f)  //状态栏和导航栏透明度，不写默认0.0f
                    .statusBarDarkFont(false)   //状态栏字体是深色，不写默认为亮色
                    .flymeOSStatusBarFontColor(R.color.bg_main_white)  //修改flyme OS状态栏字体颜色
                    .fullScreen(false)      //有导航栏的情况下，activity全屏显示，也就是activity最下面被导航栏覆盖，不写默认非全屏
                    //   .hideBar(BarHide.FLAG_HIDE_BAR)  //隐藏状态栏或导航栏或两者，不写默认不隐藏
                    .fitsSystemWindows(true)    //解决状态栏和布局重叠问题，任选其一，默认为false，当为true时一定要指定statusBarColor()，不然状态栏为透明色，还有一些重载方法
                    // .supportActionBar(true) //支持ActionBar使用
                    //  .statusBarColorTransform(R.color.orange)  //状态栏变色后的颜色
//                .navigationBarColorTransform(R.color.orange) //导航栏变色后的颜色
//                .barColorTransform(R.color.orange)  //状态栏和导航栏变色后的颜色
//                .removeSupportAllView() //移除全部view支持
                    .navigationBarEnable(true)   //是否可以修改导航栏颜色，默认为true
                    .navigationBarWithKitkatEnable(true)  //是否可以修改安卓4.4和emui3.1手机导航栏颜色，默认为true
                    .fixMarginAtBottom(true)   //已过时，当xml里使用android:fitsSystemWindows="true"属性时,解决4.4和emui3.1手机底部有时会出现多余空白的问题，默认为false，非必须
                    //  .reset()  //重置所以沉浸式参数
                    .keyboardEnable(false)  //解决软键盘与底部输入框冲突问题，默认为false，还有一个重载方法，可以指定软键盘mode
                    .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN)  //单独指定软键盘模式
                    // .keyboardMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED)  //单独指定软键盘模式
                    .setOnKeyboardListener(new OnKeyboardListener() {    //软键盘监听回调
                        @Override
                        public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
//                            LogUtils.e(isPopup);  //isPopup为true，软键盘弹出，为false，软键盘关闭
                        }
                    })
                    .init();  //必须调用方可沉浸式
        }
    }

    //城市合伙人info
    private void getMsg() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
//        params.put("token", "cf5dk4aA0GtxfnFes0rKYYnKOSfFKMU3d8qyF7VhNhbKOcpdU132XShdUyv2N8p3yiMX3rOKFso5FHfKTMG-Fso5J3fK3iMWs1cXOxZ1yjnKxcXFxcXFxcUexcXFxR7FxcXFHsXFxcUexcXFxcXFxcXFxcXFyrg");
//        cf5dk4aA0GtxfnFes0rKYYnKOSfFKMU3d8qyF7VhNhbKOcpdU132XShdUyv2N8p3yiMX3rOKFso59nfKTMG-Fso5J3fK3iMWs1cXOxZ1yjnKxcXFxcXFxcUexcXFxR7FxcXFHsXFxcUexcXFxcXFxcXFxcXFyrg
        showProgressDialog();
        addSubscription(apiStores.CityBikeCompanyStardantInterface(params),
                new ApiCallback<CityBikeCompanyStardantInterfaceResult>() {
                    @Override
                    public void onSuccess(CityBikeCompanyStardantInterfaceResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            setdata(model);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }

    private void setdata(CityBikeCompanyStardantInterfaceResult model) {
//        hehuoren_weizhitv,hehuoren_zongshourutv,hehuoren_quyudanchegouliangtv;
        hehuoren_weizhitv.setText("位置:" + model.getData().getCity());
        hehuoren_zongshourutv.setText(model.getData().getCompanyIncoming() + "");
        cantixianmoney = model.getData().getCompanyIncoming();
        try {
            hehuoren_quyudanchegouliangtv.setText(((int) model.getData().getCityBuyBikesAmount()) + "");
        } catch (Exception e) {
            hehuoren_quyudanchegouliangtv.setText((model.getData().getCityBuyBikesAmount()) + "");
            e.printStackTrace();
        }
        mFragment.clear();
        mFragment.add(f1);
        mFragment.add(f2);
        for (int i = 0; i < mTitle.size(); i++) {
            Bundle bundle = new Bundle();
            bundle.putInt("type", i);
            bundle.putString("token", preferences.getString("token", ""));
            bundle.putSerializable("model", model);
            mFragment.get(i).setArguments(bundle);
        }
        adpater = new MytablayoutvpAdapter(getSupportFragmentManager(), mTitle, mFragment);
        viewPager.setAdapter(adpater);
        //为TabLayout设置ViewPager
        tabs.setupWithViewPager(viewPager);
        //使用ViewPager的适配器
        tabs.setTabsFromPagerAdapter(adpater);
        tabs.setTabTextColors(getResources().getColor(R.color.text_main_9), getResources().getColor(R.color.radio_button_selected_color));//字体颜色
        tabs.setSelectedTabIndicatorColor(getResources().getColor(R.color.radio_button_selected_color));
        reflex(tabs);

    }

    private void setdata2(CityBikeCompanyStardantInterfaceResult model) {
//        hehuoren_weizhitv,hehuoren_zongshourutv,hehuoren_quyudanchegouliangtv;
        hehuoren_weizhitv.setText("位置:" + model.getData().getCity());
        hehuoren_zongshourutv.setText(model.getData().getCompanyIncoming() + "");
        cantixianmoney = model.getData().getCompanyIncoming();
        try {
            hehuoren_quyudanchegouliangtv.setText(((int) model.getData().getCityBuyBikesAmount()) + "");
        } catch (Exception e) {
            hehuoren_quyudanchegouliangtv.setText((model.getData().getCityBuyBikesAmount()) + "");
            e.printStackTrace();
        }
        if (f1 != null) {
            f1.datef(model);
        }
        if (f2 != null) {
            f2.datef(model);
        }
    }

    private void dataf() {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        Log.e("getMsg: ", preferences.getString("token", ""));
//        params.put("token", "cf5dk4aA0GtxfnFes0rKYYnKOSfFKMU3d8qyF7VhNhbKOcpdU132XShdUyv2N8p3yiMX3rOKFso59nfKTMG-Fso5J3fK3iMWs1cXOxZ1yjnKxcXFxcXFxcUexcXFxR7FxcXFHsXFxcUexcXFxcXFxcXFxcXFyrg");
//        cf5dk4aA0GtxfnFes0rKYYnKOSfFKMU3d8qyF7VhNhbKOcpdU132XShdUyv2N8p3yiMX3rOKFso59nfKTMG-Fso5J3fK3iMWs1cXOxZ1yjnKxcXFxcXFxcUexcXFxR7FxcXFHsXFxcUexcXFxcXFxcXFxcXFyrg
//        showProgressDialog();
        addSubscription(apiStores.CityBikeCompanyStardantInterface(params),
                new ApiCallback<CityBikeCompanyStardantInterfaceResult>() {
                    @Override
                    public void onSuccess(CityBikeCompanyStardantInterfaceResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            setdata2(model);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {

                    }
                });
    }

    private TextView tv_alltype_rengouxiexi, tv_alltype_zhuanzengxieyi, tv_alltype_zhuanzengshuoming;
    PopupWindow popupWindow;

    private void showpop(View view) {
        TextView xian;
        View popupWindowView = getLayoutInflater().inflate(R.layout.pop_xieyishuoming, null);
        popupWindow = new PopupWindow(popupWindowView, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        xian = popupWindowView.findViewById(R.id.xian);
        xian.setVisibility(View.GONE);
        tv_alltype_rengouxiexi = popupWindowView.findViewById(R.id.tv_alltype_rengouxiexi);
        tv_alltype_rengouxiexi.setText("城市合伙人介绍");
        tv_alltype_zhuanzengxieyi = popupWindowView.findViewById(R.id.tv_alltype_zhuanzengxieyi);
        tv_alltype_zhuanzengxieyi.setText("城市合伙人协议");
        tv_alltype_zhuanzengshuoming = popupWindowView.findViewById(R.id.tv_alltype_zhuanzengjiaocheng);
        tv_alltype_zhuanzengshuoming.setVisibility(View.GONE);
        tv_alltype_rengouxiexi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                Intent intent = new Intent(ChengshihehuorenActivity.this, ChengshihehuorenxiangqingActivity.class);
                intent.putExtra("show", false);
                startActivity(intent);
            }
        });
        tv_alltype_zhuanzengxieyi.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
                getWZMsg("11", "城市合伙人协议");
            }
        });
        tv_alltype_zhuanzengshuoming.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.dismiss();
            }
        });
        // 设置允许在外点击消失
        popupWindow.setOutsideTouchable(true);
        // 这个是为了点击“返回Back”也能使其消失，并且并不会影响你的背景
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        int width = metric.widthPixels;     // 屏幕宽度（像素）
        int pos = width - popupWindow.getWidth();
        popupWindow.showAsDropDown(this.findViewById(R.id.mingxi), pos, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(1f);
            }
        });
    }

    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    private void getWZMsg(String type, final String name) {
        Map<String, String> params = new HashMap<>();
        params.put("token", preferences.getString("token", ""));
        params.put("type", type);
        showProgressDialog();
        addSubscription(apiStores.GetInformationzcxy(params),
                new ApiCallback<GetCodeResult>() {

                    @Override
                    public void onSuccess(GetCodeResult model) {
                        if (model.getStatus() == Config.SUCCESSCODE) {
                            Intent i = new Intent(ChengshihehuorenActivity.this, TotalWebActivity.class);
                            i.putExtra("title", name);
                            i.putExtra("url", model.getData());
                            startActivity(i);
                        } else {
                            toastShow(model.getMessage());
                        }
                    }

                    @Override
                    public void onFailure(String msg) {
                        toastShow(msg);
                    }

                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }
}
